<?php
    defined('_JEXEC') or die('Restricted access');
    //
	//parse_infogiovani_into_mysql_table('http://www.comune.brescia.it/combs/Templates/A/V2/ControlContainer.aspx?NRMODE=Published&NRORIGINALURL=%2fIstituzionale%2fAreeESettori%2fAreaServiziAlCittadinoEInnovazione%2fGiovaniSportEdInnovazione%2fPoliticheGiovaniliEAttivitaRicreative%2fInformagiovani%2fbollettino.htm&NRNODEGUID={9AEA3614-742C-403C-82DC-7C93D005CE8A}&NRCACHEHINT=NoModifyGuest&WebSearchBox1%3AHomeSearchBoxText=Cerca%20nel%20portale%20del%20comune&__EVENTARGUMENT=&__EVENTTARGET=_ctl0_rdbOfferta_0&_ctl0%3ArdbOfferta=annunci',
		//'SitiOfferte',3,'Offerte','WebTrends=UserID=cd9cbf91-418b-471a-b97b-0f42974a793c&CreateDateUTC=18/11/2009 10.18.08&LastVisitUTC=19/11/2009 8.14.05; ASP.NET_SessionId=xqoyjo55sxotahfiwftfjk45',true);

	// Parse a html file and save into database table having a reference parent ID in $parent_table_destination_in on a parent table
	// function parse_infogiovani_into_mysql_table($html_name_link,$parent_table_name,$parent_table_ID,$table_destination_name,$required_cookie,$log)
    $html_name_link = $this->query_field(self::source_data_query_repository_name, self::source_data_query_field_siti_offerte_indirizzo_per_offerte);
   // echo $html_name_link;
    //'http://www.comune.brescia.it/combs/Templates/A/V2/ControlContainer.aspx?NRMODE=Published&NRORIGINALURL=%2fIstituzionale%2fAreeESettori%2fAreaServiziAlCittadinoEInnovazione%2fGiovaniSportEdInnovazione%2fPoliticheGiovaniliEAttivitaRicreative%2fInformagiovani%2fbollettino.htm&NRNODEGUID={9AEA3614-742C-403C-82DC-7C93D005CE8A}&NRCACHEHINT=NoModifyGuest&WebSearchBox1%3AHomeSearchBoxText=Cerca%20nel%20portale%20del%20comune&__EVENTARGUMENT=&__EVENTTARGET=_ctl0_rdbOfferta_0&_ctl0%3ArdbOfferta=annunci';
	$parent_table_name = $this->get_main_query_parameter_value(self::main_query_component_parent_table_name);
	$parent_table_ID = $this->url_argument(self::main_url_argument_row_id);
	$table_destination_name = $this->get_main_query_parameter_value(self::main_query_component_table_destination_name);
	$required_cookie = 'WebTrends=UserID=cd9cbf91-418b-471a-b97b-0f42974a793c&CreateDateUTC=18/11/2009 10.18.08&LastVisitUTC=19/11/2009 8.14.05; ASP.NET_SessionId=xqoyjo55sxotahfiwftfjk45';
	$log = false;	
	//{
		//echo PHP_VERSION;
		// Empty $table_destination_name

		$sSQL = "DELETE FROM `" . $table_destination_name . "` WHERE (`siti_offerte_id` = $parent_table_ID)";
		$oResult = mysql_query($sSQL); 
		if($oResult) 
		{
			$rss_log ='dati eliminati con successo';
		}
		else
        {
            // echo 'alert("ERRORE detail_where: '.mysql_errno().': '.mysql_error().' ");';  
            $local_error = "MySQL error ".mysql_errno().": ".mysql_error()." when executing:'$sSQL'";
            $rss_log = $local_error;
			$this->log->add_log_error($local_error,debug_backtrace());
        }
		if ($log)
			echo("$rss_log");
			
		// load rss file
		
        if ($required_cookie) 
        {
            $local_cookie = '';
            if ($required_cookie === true)
            {
                //   OTTENGO IL cookie necessario direttamente dal sito  //
                $local_url_opt = get_headers($html_name_link,0);
                //print_r($local_url_opt);
                reset($local_url_opt);
                while (next($local_url_opt) && (current($local_url_opt) != 'HTTP/1.1 200 OK'))
                {
                    //echo 'current($local_url_opt):'.current($local_url_opt);
                }
                //
                if (current($local_url_opt) == 'HTTP/1.1 200 OK')
                {
                // echo 'current($local_url_opt):'.current($local_url_opt);
                    while (next($local_url_opt))
                    {   
                        $local_pos = stripos(current($local_url_opt),"Set-Cookie:");
                        if ($local_pos === 0)
                        {
                            //echo '$local_pos'.$local_pos;
                            if ($local_cookie == '') 
                                $local_cookie = current($local_url_opt);
                            else	
                                $local_cookie = $local_cookie . current($local_url_opt);
                        }
                    }    
                }
                $local_cookie = str_replace("Set-Cookie:","",$local_cookie);
            }
            else 
            {
                $local_cookie = $required_cookie;
            }
			
            
            //echo "local_cookie: Cookie: $local_cookie\r\n";
            // Create a stream
            //echo "stringa da web Cookie: $required_cookie\r\n";
            $opts = array(
                'http'=>array(
                    'method'=>"GET",
                    'header'=> "Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3\r\n".
						"Cookie: $local_cookie\r\n"                        
                        //"Cookie: $required_cookie\r\n"
                )
            );
			//print_r($opts);
            $context = stream_context_create($opts);
           // echo 'context prima: ';
           // print_r(stream_context_get_params($context));
            $elenco_offerte = file_get_contents($html_name_link,false,$context);
        }
        else
        {
            $elenco_offerte = file_get_contents($html_name_link);
        }
		//echo 'context dopo: ';
		//print_r(stream_context_get_params($context));
		//$response = http_get($html_name_link, array("timeout"=>1), $info);
		//echo $response ;
		//echo $elenco_offerte;
		//
		$Loaded = $elenco_offerte;
		if ($Loaded)
		{
			$item_title = '';
			$item_link = '';
			$item_desc = '';
			$item_pubDate = ''; 
			$item_guid = '';
			$item_guid_isPermaLink = false;
			$item_OfferteCompleta = '';
			//
			$i = 1;
			$local_error_count = 1;
			//
			$local_start = strpos($elenco_offerte,'<label name="profilo">',$local_stop);
			while ($local_start)
			{
				$local_current_item_log = "elemento ".($i)."<br>";
				// data pubblicazione
				$local_start = strpos($elenco_offerte,'<span id="_ctl0_IntestazioneIL1_lblNumData" class="Wz_Label">');
				$local_stop = strpos($elenco_offerte,'</span>',$local_start);
				$item_pubDate = strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));	
                $item_pubDate = substr($item_pubDate,-10,10);
				// datore
				$local_start = strpos($elenco_offerte,'<label name="datore'.$i.'">');
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));	
				// indirizzo
				$local_start = strpos($elenco_offerte,'<label name="indirizzo'.$i.'">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// cap
				$local_start = strpos($elenco_offerte,'<label name="cap'.$i.'">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// citta
				$local_start = strpos($elenco_offerte,'<label name="citta'.$i.'">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// settore label
				$local_start = strpos($elenco_offerte,'<label name="settore">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// settore
				$local_start = strpos($elenco_offerte,'<label name="settore'.$i.'">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// numeroposti label
				$local_start = strpos($elenco_offerte,'<label name="posti">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// numeroposti
				$local_start = strpos($elenco_offerte,'<label name="numeroposti'.$i.'">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// profilo label
				$local_start = strpos($elenco_offerte,'<label name="profilo">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// profilo
				$local_start = strpos($elenco_offerte,'<label name="profilo'.$i.'">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_title = strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				$item_OfferteCompleta = $item_OfferteCompleta . $item_title;
				// requisiti label
				$local_start = strpos($elenco_offerte,'<label name="settore">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// requisiti
				$local_start = strpos($elenco_offerte,'<label name="requisiti'.$i.'">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// note
				$local_start = strpos($elenco_offerte,'<label name="note'.$i.'">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// fonte label
				$local_start = strpos($elenco_offerte,'<label name="fonte">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				// fonte
				$local_start = strpos($elenco_offerte,'<label name="fonte'.$i.'">',$local_stop);
				$local_stop = strpos($elenco_offerte,'</label>',$local_start);
				$item_OfferteCompleta = $item_OfferteCompleta . strip_tags(substr($elenco_offerte,$local_start,$local_stop - $local_start));
				
				
		
				// save to DB
				$sSQL = "INSERT INTO `$table_destination_name` ( 
					`siti_offerte_id` , `offerte_title` , 
					`offerte_link` , 
					`offerte_description` , `offerte_pub_date`,
					`offerte_guid` , `offerte_guid_is_perma_link` ,
					`offerte_offerta_completa`)
					VALUES (
					'$parent_table_ID', '$item_title', '$item_link','$item_desc', '$item_pubDate', 
					'$item_guid','$item_guid_isPermaLink','$item_OfferteCompleta');";
		
				
				//echo("$local_current_item_log");
				//
				$oResult = mysql_query($sSQL); 
				if($oResult) 
				{
				
					$rss_result = self::result_separator_charater.$i.self::result_separator_charater;
					$rss_log ='dati inseriti con successo<br>';
					echo $rss_result; 
					//echo "tab1_Comp.render ();";
				} 
				else
                {
                    $rss_result = self::result_error_separator_charater.$local_error_count.self::result_error_separator_charater;
					echo $rss_result;
					$local_error_count++;
					// echo 'alert("ERRORE detail_where: '.mysql_errno().': '.mysql_error().' ");';  
                    $local_error = "MySQL error ".mysql_errno().": ".mysql_error()." when executing:'$sSQL'";
                    $rss_log = $local_error;
					$this->log->add_log_error($local_error,debug_backtrace());
                }
				if ($log)
					echo("$rss_log");
				
				//
				$local_start = strpos($elenco_offerte,'<label name="profilo">',$local_stop);
				$i++;
			}
		}
		else
		{
			if ($log)
			{
				$rss_log ='Impossibile caricare il il file: "'.$rss_name_link.'" a causa di: ';
			}
			echo("$rss_log");			
		}	
	//}	
	
	
?>